package start.demo01.datatype.json.entity.editor.jsonEditor;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import start.demo01.datatype.json.interfaces.JSONEditor;
import start.demo01.datatype.json.json.JSONPath;
import start.demo01.datatype.json.pool.CacheMap;

import java.util.Iterator;
import java.util.Map;

import static start.demo01.datatype.json.constant.Constant.F;

//字段转移
public class JSONCopyEditor extends JSONEditor {

    //copy(map,,*)
    public JSONCopyEditor(String args) {
        super(args);
    }

    {
        name = "COPY";
    }

    @Override
    protected void operationObject(JSONObject object, String key) {
        return;
    }

    @Override
    protected void operationArray(JSONArray array, int index) {
        return;
    }

    @Override
    protected void operation(JSONObject object) {
        //args=map,test.val,*
        String[] split = args.split(",");
        JSONPath jsonPath = JSONPath.builder(null,split[0], split[1]);
        jsonPath.setMap(map);
        jsonPath.editor();
        JSONObject jsonObject = (JSONObject) jsonPath.getCurrent();
        JSONPath.Node last = jsonPath.getNodes().getLast();
        if (last.getKey() != null)
            jsonObject = jsonObject.getJSONObject(last.getKey());
        if (F.equals(split[2])) {
            Iterator<Map.Entry<String, Object>> iterator = object.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> next = iterator.next();
                jsonObject.put(next.getKey(), next.getValue());
            }
            return;
        }
        for (int i = 2; i < split.length; i++) {
            String s = split[i];
            jsonObject.put(s, object.get(s));
        }
    }
}
